package com.example.proxy;

import com.example.annotation.Transactional;
import com.example.manager.TransactionManager;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibTransactionInterceptor implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        if (method.isAnnotationPresent(Transactional.class) || 
            method.getDeclaringClass().isAnnotationPresent(Transactional.class)) {
            try {
                TransactionManager.begin();
                Object result = proxy.invokeSuper(obj, args);
                TransactionManager.commit();
                return result;
            } catch (Exception e) {
                TransactionManager.rollback();
                throw e;
            }
        }
        return proxy.invokeSuper(obj, args);
    }
}